package com.example.demo.restcontroller;


import com.example.demo.config.RandomValidateCodeUtil;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

//解决跨域请求的问题
@CrossOrigin
@RestController
public class LoginRestController {

    @Autowired
    UserService userService;

    @PostMapping("/login")
    public Map<String, Object> login(User user) {
        HashMap<String, Object> map = new HashMap<>();
        User reUser = userService.selectUserByUser(user);
        if (reUser != null) {
            map.put("code", 200);
            map.put("obj", reUser);
        } else {
            map.put("code", -1);
        }
        return map;
    }


    private final static Logger logger = LoggerFactory.getLogger(LoginRestController.class);


    /*******************************验证码逻辑*******************************************************************?/
     /**
     * 生成验证码
     */
    @GetMapping("/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {

        try {

            //设置相应类型,告诉浏览器输出的内容为图片
            response.setContentType("image/jpeg");

            //设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);

            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();

            //输出验证码图片方法
            randomValidateCode.getRandomCode(request, response);

        } catch (Exception e) {
            logger.error("获取验证码失败>>>>   ", e);
        }

    }

    /**
     * 校验验证码
     */
    @ResponseBody
    @PostMapping("/checkVerify")
    public boolean checkVerify(@RequestParam String verifyInput, HttpServletRequest request) {
        try {

            //从session中获取随机数
            String inputStr = verifyInput;


            if (!RandomValidateCodeUtil.vcode.equalsIgnoreCase(inputStr)) {
                return false;
            } else {
                return true;
            }

        } catch (Exception e) {
            logger.error("验证码校验失败", e);
            return false;
        }
    }

}
